import os
import shutil
import re

SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],

             1024 :   [ 'KiB' ,   'MiB' ,   'GiB' ,   'TiB' ,   'PiB' ,   'EiB' ,   'ZiB' ,   'YiB' ]} 
 
def  approximate_size ( size ,  a_kilobyte_is_1024_bytes = True ): 
    '''Convert a file size to human-readable form.

    Keyword arguments:
    size -- file size in bytes
    a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
                                if False, use multiples of 1000

    Returns: string

    ''' 
    if  size  <   0 : 
        raise   ValueError ( 'number must be non-negative' ) 

    multiple  =   1024   if  a_kilobyte_is_1024_bytes  else   1000 
    for  suffix  in  SUFFIXES [ multiple ]: 
        size  /=  multiple
        if  size  <  multiple : 
            return   '{0:.1f} {1}' . format ( size ,  suffix ) 

    raise   ValueError ( 'number too large' )



# def un_zip(file_name, root, task_id):
#     """
#     filename: 压缩文件路径
#     root: 解压文件夹路径
#     task_id: 任务id
#     """
#     os.makedirs(root, exist_ok=True)
#     zip_file = zipfile.ZipFile(file_name)
#     file_num = len(zip_file.namelist())
#     for i in range(file_num):
#         file = zip_file.namelist()[i]
#         zip_file.extract(file, root)
#         progress = int((i+1)*100/file_num)
#         redis.set(task_id, progress)
#     zip_file.close()


def rm_dir(dir_path):
    if(os.path.exists(dir_path)):
        shutil.rmtree(dir_path)


def rm_file(file_path):
    if(os.path.exists(file_path)):
        os.remove(file_path)


def rename_pmi(wafer_dir, image_name):
    pattern = r'[^a-zA-Z0-9.]'  # 匹配非数字、非英文字母和非句点的字符
    new_filename = re.sub(pattern, '.', image_name)
    new_filepath = os.path.join(wafer_dir, new_filename)

    os.rename(os.path.join(wafer_dir, image_name), new_filepath)

    return new_filename



